const Router = require('koa-router');
const router = new Router({ prefix: '/api/vaccine' });
const { VaccineAppointment } = require('../models/vaccineAppointmentModels');
const { Clinic } = require('../models/clinicModel');

// 提交疫苗预约
router.post('/appointment', async (ctx) => {
  try {
    const appointmentData = ctx.request.body;
    // console.log('预约数据:', appointmentData);
    // 查找当前条件下的所有预约记录
    const existingAppointments = await VaccineAppointment.findAll({
      where: {
        vaccineType: appointmentData.vaccineType,
        vaccine: appointmentData.vaccine,
        clinic: appointmentData.clinic,
        date: appointmentData.date,
        time: appointmentData.time
      }
    });
    // console.log('已存在的预约记录:', existingAppointments);
    // 计算当前已预约数量
    const currentCount = existingAppointments.length;
    // 设置当前预约的availableCount为总数减去已预约数再减1
    // 假设初始availableCount为appointmentData.availableCount
    const updatedAvailableCount = Math.max(0, appointmentData.availableCount - currentCount - 1);
    
    // 创建新的预约记录
    const newAppointment = await VaccineAppointment.create({
      vaccineType: appointmentData.vaccineType,
      vaccine: appointmentData.vaccine,
      clinic: appointmentData.clinic,
      date: appointmentData.date,
      time: appointmentData.time,
      availableCount: updatedAvailableCount
    });
    
    // 更新诊所的可用预约数量
    const clinic = await Clinic.findOne({
      where: {
        name: appointmentData.clinic
      }
    });
    
    if (clinic) {
      await clinic.update({
        availableCount: updatedAvailableCount
      });
    }
    
    ctx.status = 200;
    ctx.body = {
      code: 200,
      message: '疫苗预约成功',
      data: newAppointment
    };
  } catch (error) {
    console.error('疫苗预约失败：', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '预约失败，请稍后重试',
      error: error.message
    };
  }
});

// 获取用户的所有预约记录
router.get('/appointments', async (ctx) => {
  try {
    const appointments = await VaccineAppointment.findAll();
    ctx.status = 200;
    ctx.body = {
      code: 200,
      message: '获取预约记录成功',
      data: appointments
    };
  } catch (error) {
    console.error('获取预约记录失败：', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '获取预约记录失败，请稍后重试'
    };
  }
});

// 更新预约状态
router.put('/appointments/:id/status', async (ctx) => {
  try {
    const { id } = ctx.params;
    const { status } = ctx.request.body;
    
    console.log('更新预约状态 - ID:', id, '状态:', status);
    
    // 验证状态值
    const validStatuses = [1, 2, 3]; // 1-预约成功，2-已取消，3-已完成
    if (!status || !validStatuses.includes(Number(status))) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '无效的状态值，请使用1、2或3'
      };
      return;
    }
    
    // 查找并更新预约记录
    const appointment = await VaccineAppointment.findByPk(id);
    
    if (!appointment) {
      ctx.status = 404;
      ctx.body = {
        code: 404,
        message: '未找到对应的预约记录'
      };
      return;
    }
    
    // 更新状态
    await appointment.update({
      status: Number(status)
    });
    
    ctx.status = 200;
    ctx.body = {
      code: 200,
      message: '预约状态更新成功',
      data: appointment
    };
  } catch (error) {
    console.error('更新预约状态失败：', error);
    console.error('错误堆栈：', error.stack);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '更新状态失败，请稍后重试',
      error: error.message,
      stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
    };
  }
});

module.exports = router;

